/*
 * @lc app=leetcode.cn id=111 lang=typescript
 *
 * [111] 二叉树的最小深度
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function minDepth(root: TreeNode | null): number {
    if (!root) return 0;
    let min = Infinity;
    const keepGoing = (sub: TreeNode, sum: number) => {
        const colVal = sum + 1;
        if (!sub.right && !sub.left) {
            if (min > colVal) min = colVal;
            return;
        }
        if (sub.left) {
            keepGoing(sub.left, colVal);
        }
        if (sub.right) {
            keepGoing(sub.right, colVal);
        }
    };
    keepGoing(root, 0);
    return min;
}

// @lc code=end
